package com.scr1pt.extension

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject

/**
 * 说明: JSON扩展
 *
 * 创建者: tum0r
 *
 * 时间: 2021/10/31 15:57
 */

/**
 * 将JSONArray转为JSONObject集合
 */
fun JSONArray.getAllJSONObjects(): ArrayList<JSONObject> {
    val result = ArrayList<JSONObject>(this.size)
    for (json in this) result.add(JSONObject.parseObject(JSON.toJSONString(this[0])))
    return result
}

/**
 * 将JSON数组转为强类型对象集合
 *
 * @param[targetClass] 目标强类型
 * @param[start] 字段的开始下标
 * @param[end] 字段的结束下标
 */
@JvmOverloads
fun <T> JSONArray.toObjects(targetClass: Class<T>, start: Int = 0, end: Int = if (this.size > 0) this.getJSONObject(0).size else 0): ArrayList<T> {
    val result = ArrayList<Array<Any?>>()
    val jsonObjects = this.getAllJSONObjects()
    if (jsonObjects.size > 0) {
        val columnCount = jsonObjects[0].size
        val columnName = Array(columnCount) { "" }
        for ((index, key) in jsonObjects[0].keys.withIndex())
            columnName[index] = key
        result.add(columnName as Array<Any?>)
        for (json in jsonObjects) {
            val item = Array<Any?>(columnCount) { null }
            for (i in 0 until columnCount)
                item[i] = json.getOrDefault(columnName[i], null)
            result.add(item)
        }
    }
    return result.arrayToObjects(targetClass, start, end)
}

/**
 * 将JSON数组转为强类型对象集合
 *
 * @param[start] 字段的开始下标
 * @param[end] 字段的结束下标
 */
@JvmOverloads
inline fun <reified T> JSONArray.toObjects(start: Int = 0, end: Int = if (this.size > 0) JSONObject.parseObject(JSON.toJSONString(this[0])).size else 0): ArrayList<T> = this.toObjects(T::class.java, start, end)